package com.cxg.fairy.ec.detail;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.cxg.fairy.app.AccountManager;
import com.cxg.fairy.delegates.LatteDelegate;
import com.cxg.fairy.ec.main.cart.ShopCartDelegate;
import com.cxg.fairy.ec.main.cart.SignleShopCartDelegate;
import com.cxg.fairy.net.RestClient;
import com.cxg.fairy.net.callback.ISuccess;
import com.cxg.fairy.ui.animation.BezierAnimation;
import com.cxg.fairy.ui.animation.BezierUtil;
import com.cxg.fairy.ui.widget.CircleTextView;
import com.cxg.fairy.util.log.LatteLogger;
import com.cxg.fairy.util.toasty.Toasty;
import com.daimajia.androidanimations.library.YoYo;
import com.diabin.latte.ec.R;
import com.diabin.latte.ec.R2;
import com.joanzapata.iconify.widget.IconTextView;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by gabrielsung on 2018/4/6 0006.
 */

public class IGoodsDetailDelegate extends LatteDelegate implements
        AppBarLayout.OnOffsetChangedListener,
        BezierUtil.AnimationListener{

    private static final String ARG_GOODS_ID = "ARG_GOODS_ID";

    @BindView(R2.id.tab_layout)
    TabLayout mTabLayout = null;

    @BindView(R2.id.view_pager)
    ViewPager mViewPager = null;

    //底部
    @BindView(R2.id.icon_favor)
    IconTextView mIconFavor = null;
    @BindView(R2.id.tv_favor)
    AppCompatTextView mTvFavor = null;
    @BindView(R2.id.tv_shopping_cart_amount)
    CircleTextView mCircleTextView = null;
    @BindView(R2.id.rl_add_shop_cart)
    RelativeLayout mRlAddShopCart = null;
    @BindView(R2.id.icon_shop_cart)
    IconTextView mIconShopCart = null;

    private String mGoodsThumbUrl = null;
    private int mShopCount = 0;
    final String UUID = AccountManager.getSignUUID();

    private boolean inListTag = false;

    @OnClick(R2.id.back_home)
    void onClickBackHome() {
        getSupportDelegate().pop();
    }

    private static final RequestOptions OPTIONS = new RequestOptions()
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .centerCrop()
            .dontAnimate()
            .override(100, 100);

    @Override
    public Object setLayout() {
        return R.layout.delegate_goods_detail_i;
    }

    public static IGoodsDetailDelegate create(int goodsId) {
        final Bundle args = new Bundle();
        args.putInt(ARG_GOODS_ID, goodsId);
        final IGoodsDetailDelegate delegate = new IGoodsDetailDelegate();
        delegate.setArguments(args);
        return delegate;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        mCircleTextView.setCircleBackground(Color.RED);
        initData();
        initTabLayout();
    }

    private void initTabLayout() {
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        mTabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(getContext(), R.color.favorListTag));
        mTabLayout.setTabTextColors(Color.parseColor("#565656"),Color.BLACK);
        mTabLayout.setBackgroundColor(Color.WHITE);
        mTabLayout.setupWithViewPager(mViewPager);
    }

    private void initPager(JSONObject data) {
        final PagerAdapter adapter = new TabPagerAdapter(getFragmentManager(), data);
//        mViewPager.setOffscreenPageLimit(3);
        mViewPager.setAdapter(adapter);
    }

    private void initData() {
        RestClient.builder()
                .url("getGoodsDetail")
                .params("skuId",getArguments().getInt(ARG_GOODS_ID))
                .params("uuid", UUID)
                .loader(getContext())
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        final JSONObject data = JSON.parseObject(response).getJSONObject("data");
                        initPager(data);
                        initListTag(data);
                        setShopCartCount(data);
                    }
                })
                .build()
                .post();
    }


    /**
     * addToShortCart
     */
    @OnClick(R2.id.rl_add_shop_cart)
    void onClickAddShopCart() {
        final CircleImageView animImg = new CircleImageView(getContext());
        Glide.with(this)
                .load(mGoodsThumbUrl)
                .apply(OPTIONS)
                .into(animImg);
        BezierAnimation.addCart(this, mRlAddShopCart, mIconShopCart, animImg, this);
    }

    private void setShopCartCount(JSONObject data) {
        mGoodsThumbUrl = data.getString("thumb");
        if (mShopCount == 0) {
            mCircleTextView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onAnimationEnd() {
        YoYo.with(new ScaleUpAnimator())
                .duration(500)
                .playOn(mIconShopCart);
        RestClient.builder()
                .url("addToShoppingCart")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        if (true) {
                            mShopCount++;
                            mCircleTextView.setVisibility(View.VISIBLE);
                            mCircleTextView.setText(String.valueOf(mShopCount));
                            Toasty.success(getContext(), "添加购物车成功!").show();
                        }
                    }
                })
                .params("uuid",UUID)
                .params("skuId",getArguments().getInt(ARG_GOODS_ID))
                .build()
                .post();
    }

    private void initListTag(JSONObject data) {
        inListTag = data.getBoolean("inList");
        if (inListTag) {
            mIconFavor.setText("{icon-goods-like-fill}");
            mTvFavor.setText("已喜欢");
            mIconFavor.setTextColor(getContext().getResources().getColor(R.color.favorTag));
        }
    }

    @SuppressWarnings("deprecation")
    @OnClick(R2.id.rl_favor)
    public void doFavor() {
        if(!inListTag){
            mIconFavor.setText("{icon-goods-like-fill}");
            mTvFavor.setText("已喜欢");
            mIconFavor.setTextColor(getContext().getResources().getColor(R.color.favorTag));
            inListTag = true;
        }else{
            mIconFavor.setText("{icon-goods-like}");
            mTvFavor.setText("喜欢");
            mIconFavor.setTextColor(getContext().getResources().getColor(R.color.noFavorTag));
            inListTag = false;
        }
        postFavor();
    }

    @OnClick(R2.id.rl_shop_cart)
    public void gotoShopCart() {
        getSupportDelegate().start(new ShopCartDelegate());
    }

    public void postFavor() {

        RestClient.builder()
                .url("insert_del_favorite")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        final boolean isFavor = JSON.parseObject(response).getBoolean("isFavor");
                        LatteLogger.e(this.toString(),response);
                        if (isFavor) {
                            //reality action doFavor
                        }
                    }
                })
                .params("uuid", UUID)
                .params("skuId",getArguments().getInt(ARG_GOODS_ID))
                .params("isFavor",inListTag)
                .build()
                .post();
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

    }
}
